import 'package:flutter/material.dart';

/// 一个通用的、可自定义列表项的滚动选择器组件。
/// 它基于 `ListWheelScrollView` 构建，并将 item 的构建委托给外部。
class CustomPicker extends StatefulWidget {
  final int startValue;
  final int endValue;
  final int initialValue;
  final ValueChanged<int> onValueChanged;
  final Widget Function(BuildContext context, int value, bool isSelected)
  itemBuilder;

  const CustomPicker({
    super.key,
    required this.startValue,
    required this.endValue,
    required this.initialValue,
    required this.onValueChanged,
    required this.itemBuilder,
  });

  @override
  State<CustomPicker> createState() => _CustomPickerState();
}

class _CustomPickerState extends State<CustomPicker> {
  late FixedExtentScrollController _scrollController;
  late int _selectedValue;

  @override
  void initState() {
    super.initState();
    _selectedValue = widget.initialValue;
    _scrollController = FixedExtentScrollController(
      initialItem: _calculateInitialItem(),
    );
  }

  int _calculateInitialItem() {
    final value = widget.initialValue.clamp(widget.startValue, widget.endValue);
    return value - widget.startValue;
  }

  @override
  void didUpdateWidget(CustomPicker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialValue != oldWidget.initialValue ||
        widget.startValue != oldWidget.startValue ||
        widget.endValue != oldWidget.endValue) {
      _selectedValue = widget.initialValue;
      final targetItem = _calculateInitialItem();

      // 确保控制器有客户端时才跳转
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients &&
            _scrollController.selectedItem != targetItem) {
          // 使用 animateToItem 而不是 jumpToItem 可以提供更平滑的过渡
          _scrollController.animateToItem(
            targetItem,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        }
      });
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final int itemCount = widget.endValue - widget.startValue + 1;

    return SizedBox(
      height: 120,
      child: Center(
        child: ListWheelScrollView.useDelegate(
          controller: _scrollController,
          itemExtent: 40,
          physics: const FixedExtentScrollPhysics(),
          magnification: 1.0,
          useMagnifier: false,
          overAndUnderCenterOpacity: 0.5,
          perspective: 0.001,
          onSelectedItemChanged: (index) {
            final newValue = widget.startValue + index;
            setState(() {
              _selectedValue = newValue;
            });
            widget.onValueChanged(newValue);
          },
          childDelegate: ListWheelChildBuilderDelegate(
            builder: (context, index) {
              if (index < 0 || index >= itemCount) {
                return const SizedBox.shrink();
              }
              final int value = widget.startValue + index;
              final bool isSelected = (value == _selectedValue);
              return widget.itemBuilder(context, value, isSelected);
            },
            childCount: itemCount,
          ),
        ),
      ),
    );
  }
}
